// MQTT服务类
import mqtt, { MqttClient, IClientOptions, IClientSubscribeOptions } from 'mqtt';

// MQTT 配置（使用接口定义类型）
const defaultOptions: IClientOptions = {
  clean: true,
  connectTimeout: 4000,
  clientId: 'mes-client-' + Math.random().toString(16).substr(2, 8),
  username: 'admin', // 如果需要认证
  password: 'password123'
};

// 定义消息回调函数类型
type MessageCallback = (topic: string, message: string) => void;

export class MQTTClient {
  private client: MqttClient | null = null;
  private brokerUrl: string;
  private options: IClientOptions;
   private messageCallbacks: MessageCallback[] = [];    
  constructor(brokerUrl: string, options?: IClientOptions) {
    this.brokerUrl = brokerUrl;
    this.options = { ...defaultOptions, ...options };
  }
 

 public connect(): void {
    this.client = mqtt.connect(this.brokerUrl, this.options);

    // 连接成功
    this.client.on('connect', (connack) => {
      console.log('MQTT Connected successfully', connack);
      this.subscribe('your/topic');
    });

    // 错误处理
    this.client.on('error', (error) => {
      console.error('MQTT Error occurred:', error);
    });

    // 重新连接
    this.client.on('reconnect', () => {
      console.log('MQTT Trying to reconnect...');
    });

    // 断开连接
    this.client.on('close', () => {
      console.log('MQTT Connection closed');
    });

    // 离线状态
    this.client.on('offline', () => {
      console.log('MQTT Client is offline');
    });

    // 接收消息并触发所有注册的回调
    this.client.on('message', (topic: string, message: Buffer) => {
   
      // 将消息转换为字符串并分发给所有注册的回调函数
      const messageStr = message.toString();
         console.log(`接收到消息 ${topic} ${messageStr}`);
      this.messageCallbacks.forEach(callback => {
        callback(topic, messageStr);
      });
    });

  }

 public subscribe(topic: string | string[], opts: IClientSubscribeOptions = { qos: 0 }): void {
    if (!this.client) {
      console.error('MQTT Client not connected');
      return;
    }

    this.client.subscribe(topic, opts, (err) => {
      if (!err) console.log(`Subscribed to ${topic}`);
    });
  }

  // 接收消息处理
   onMessage(callback: MessageCallback): void {
    if (!this.client) {
      console.error('MQTT Client not connected');
      return;
     }
   ;
  }

  

  // 发送消息
 public  publish(topic: string, message: string, opts: { qos: number } = { qos: 0 }): void {
    if (!this.client) {
      console.error('MQTT Client not connected');
      return;
    }

    this.client.publish(topic, message);
  }

 public disconnect(): void {
    this.client?.end(true, () => {
      console.log('MQTT Disconnected');
    });
  }
}

// 创建实例（需要传入 broker URL）
export const mqttClient = new MQTTClient(import.meta.env.VITE_MQTT_BrokerUrl);